<?php

namespace MoChat\App\Call\Command;

use Hyperf\Command\Command as HyperfCommand;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;
use MoChat\App\Call\Model\CallPlan;
use MoChat\App\Call\Model\CallPlanWorkContact;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
use TheSeer\Tokenizer\Exception;
use Hyperf\Command\Annotation\Command;

/**
 * 遗漏任务
 * @Command
 */
class CallOmissionCommand extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

        parent::__construct('callOmission');
    }

    public function configure()
    {
        parent::configure();
        $this->addOption('clear', 'C', InputArgument::OPTIONAL, '清除redis', 0);
        $this->setDescription('遗漏任务');
    }

    private function processing($data, $nextId)
    {
        if (!empty($data)) {
            $data=$data->toArray();
            $arr = [];
            $ids=array_column($data,'id');
            foreach ($data as $value) {
                $arr[] = [
                    "corp_id" => $value['corpId'],
                    "call_plan_id" => $nextId,
                    "created_at" => date('Y-m-d H:i:s'),
                    "client_id" => $value['clientId'],
                    "is_omission" => 1,//是遗漏任务
                    "top_call_plan_id" => $value['callPlanId'],
                ];
            }
            if (!empty($arr)) {
                CallPlanWorkContact::insert($arr);
                CallPlanWorkContact::whereIn('id',$ids)->update([
                    'transfer'=>1,//已转移
                    'is_omission'=>1,//遗漏任务
                ]);
            }
        }
    }

    public function handle()
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(Redis::class);
        $clear = $this->input->getOption('clear');
        if ($clear) {
            $redis->del('CallOmissionCommand_key');
        }
        $bool = $redis->get('CallOmissionCommand_key');
        if ($bool) {
            $this->line('上一个销售任务同步脚本程序正在执行中', 'info');
        } else {
            $redis->set('CallOmissionCommand_key', true);
            Db::beginTransaction();
            try {
                $nowTime = date('Y-m-d');
                $nextId = CallPlan::where('plan_time', '>', $nowTime)->orderBy(Db::raw('plan_time-NOW()'), 'asc')->value('id');
                CallPlan::where('call_plan.plan_time', '<', $nowTime)
                    ->join('call_plan_work_contact as client', 'client.call_plan_id', 'call_plan.id')
                    ->where('client.status', 0)//未已经拨打
                    ->where('client.transfer', 0)//未转移
                    ->where('call_plan.is_export_next_task', 1)
                    ->select([
                        'client.*',
                    ])
                    ->chunk(100, function ($data) use ($nextId) {
                        $this->processing($data, $nextId);
                    });
                Db::commit();
            } catch (\Throwable $throwable) {
                Db::rollBack();
            }
            $redis->del('CallOmissionCommand_key');
            $this->line('遗漏任务处理完成', 'info');
        }
    }
}